package com.itheima.job;


import com.itheima.health.common.RedisConst;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class CleanTask {

    //最大允许存放时间30秒
    private final static Long MAX_TIME = 30 * 1000L;
    @DubboReference
    private SetmealService setmealService;

    @Autowired
    QiniuUtils qiniuUtils;

    @Autowired
    RedisTemplate redisTemplate;
    @Scheduled(cron = "0/5 * * * * ?")
    public void cleanImage(){
        log.info("定时任务开始执行");
        //从redis获取图片集合  members 获取set集合所有
        Set<String> members = redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).members();
        //获取文件名
        for (String fileName: members) {
            //截取时间戳
            String[] split = fileName.split("_");
            log.info("split截取的时间戳："+split[0]);
            //存到redis的时间戳
            Long creatTime = Long.valueOf(split[0]);
            //取差
            if((System.currentTimeMillis()-creatTime)<MAX_TIME){
                //放行
                log.info("文件没有超时忽略不删除fileName:{ }",fileName);
                continue;
            }
            //根据filename查询数据库有没有引用
            int count = setmealService.count(fileName);
            if(count==0){
                //没有使用删除  七牛云删除
                qiniuUtils.deleteFileFromQiniu(fileName);
                log.info("文件没有被使用从七牛云中删除fileName:{ }",fileName);
            }
            //从redis中删除（有使用但是存到redis超时）
            log.info("文件在redis中超时，从redis中删除fileName:{ }",fileName);
            redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(fileName);
        }
    }
}
